package com.tian.common.config;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-12-13 9:59
 * {@code @version:} 1.0
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * 创建ThreadPoolTaskScheduler Bean
 */
@Slf4j
@Configuration
public class DynamicThreadPoolTaskConfig {

    @Value("${thread-pool.core-size}")
    private int coreSize;
    @Value("${thread-pool.scheduler.core-size}")
    private int coreScheduleSizer;

    @Value("${thread-pool.max-size}")
    private int maxSize;

    @Value("${thread-pool.queue-capacity}")
    private int queueCapacity;

    @Value("${thread-pool.await-termination-seconds}")
    private int awaitTerminationSeconds;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        //线程池大小
        threadPoolTaskScheduler.setPoolSize(coreScheduleSizer);
        //线程名称前缀
        threadPoolTaskScheduler.setThreadNamePrefix("charge-station-taskSchedulerExecutor-");
        //等待时长
        threadPoolTaskScheduler.setAwaitTerminationSeconds(awaitTerminationSeconds);
        //关闭任务线程时是否等待当前被调度的任务完成
        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        //自定义拒绝策略
        threadPoolTaskScheduler.setRejectedExecutionHandler((r, executor) -> {
            //当线程池队列已满时，新任务会被拒绝执行，这里可以做一些日志记录或者抛出异常
            log.error("线程池队列已满，新任务被拒绝执行，threadName:{}", Thread.currentThread().getName());
        });
        return threadPoolTaskScheduler;
    }
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(coreSize);
        executor.setMaxPoolSize(maxSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("charge-station-dynamicTaskExecutor-");
        executor.initialize();
        executor.setRejectedExecutionHandler((r, executor1) -> log.error("任务" + r + "被拒绝执行"));
        return executor;
    }
}
